function [res s1] = cost (p, F, X, varargin)

   ## usage:  res = cost (p, F, X, varargin)
   ##
   ## cost function of problem defined by F

   global PAR

   x = X(:,1) ; y = X(:,2) ;

   if (exist([F "cdf"]) == 2 && exist([F "inv"]) == 2)
      FD = prb(F, x, p, varargin{:}) ; FI = prb_inv(F, y, p, varargin{:}) ;
   else
      FD = feval(F, x, p, varargin{:}) ; FI = feval([F "_inv"], y, p, varargin{:}) ;
   endif 
   if !(isreal(FD) & isreal(FI))
      res = Inf ; return ;
   endif 

   if (all(!isfinite(y - FD)) || all(!isfinite(x - FI)))
      res = inf ;
      return ;
   endif 

   s1 = rms(y-FD) ;
   res1 = rms(y - FD) / rms(y) ;
   res2 = rms(x - FI) / rms(x) ;

   if (nargin < 6)
      w = [0.5 0.5] ;
   else
      w = varargin{3} ;
   endif

   res = w(1)*res1 + w(2)*res2 ;
   res = min(res,Inf) ;

endfunction
